package org.syncsoft.overalt.socket;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Date;

import org.syncsoft.overalt.gui.api.GuiWindowControll;

/**
 * 
 * @author tptfc
 *
 */
public class ListenerSocket extends Thread {
	private Socket socket;
	private boolean running;
	private final long maxTime = 60000 * 15;
	
	public ListenerSocket(Socket socket) {
		setSocket(socket);
	}
	
	public void stopListenerSocket() {
		setRunning(false);
	}
	
	@Override
	public void run() {
		setRunning(true);
		InputStreamReader inputStream = null;
		OutputStreamWriter outputStream = null;
		
		try {
			inputStream = new InputStreamReader(getSocket().getInputStream());
			outputStream = new OutputStreamWriter(getSocket().getOutputStream());
			
			Date date = new Date();
			
			while(isRunning()) {
				int msgSize = getSocket().getInputStream().available();
				StringBuffer buffer = new StringBuffer();

				for(int i = 0; i < msgSize; i++) {
					buffer.append((char) inputStream.read());
				}

				if (!buffer.toString().trim().isEmpty() && ! isQuit(buffer.toString().trim()) && ! isExpiradTime(date)) {
					GuiWindowControll.execute(buffer.toString().trim());
					outputStream.flush();
				}
				
				sleep(150);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			closeStream(inputStream);
			closeStream(outputStream);
			closeSocket();
		}
	}

	/**
	 * 
	 */
	private void closeSocket() {
		if (getSocket() != null) {
			try {
				getSocket().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 
	 * @param stream
	 */
	private void closeStream(Closeable stream) {
		if (stream != null) {
			try {
				stream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * Expired 
	 * @return
	 */
	private boolean isExpiradTime(Date date) {
		boolean expirad = false;
		
		Date currentDate = new Date();
				
		
		if (currentDate.getTime() - date.getTime() > maxTime) {
			setRunning(false);
			expirad = true;
		}
		
		return expirad;
	}
	
	private boolean isQuit(String message) {
		boolean quit = false;
		
		if ("quit".equals(message)) {
			setRunning(false);
			quit = true;
		}
		
		return quit;
	}
	
	private Socket getSocket() {
		return socket;
	}
	private void setSocket(Socket socket) {
		this.socket = socket;
	}

	private boolean isRunning() {
		return running;
	}

	private void setRunning(boolean running) {
		this.running = running;
	}
}
